<template>
  <div ref="taskLog" class="task-log">
    <a-modal
      title="日志"
      :body-style="{ padding: '20px' }"
      :visible="visible"
      @cancel="onClose"
      @ok="onClose"
      :width="1000"
      :get-container="() => $refs.taskLog as any"
      destroy-on-close
      :maskClosable="false"
    >
      <TerminalLog :url="logUrl" ref="terminalLogRef" v-if="visible" />
      <template #footer>
        <div class="footer">
          <div class="download" @click="downloadLog">
            <download-outlined />
            下载
          </div>
        </div>
      </template>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { DownloadOutlined } from '@ant-design/icons-vue';
import { download, getFileNameFromContentDisposition } from '@/utils';
import { getTaskLog } from '@/api/pipeline';
const visible = ref(false);
const logUrl = ref();

const onOpen = (data: string) => {
  visible.value = true;
  // 拼上devops前缀
  logUrl.value = `/devops${data}`;
};

const onClose = () => {
  visible.value = false;
};

const getParamsStr = () => {
  if (!logUrl.value) return '';

  return logUrl.value.slice(logUrl.value.indexOf('?'));
};

const downloadLog = async () => {
  const res = await getTaskLog(getParamsStr());
  const blob = new Blob([res.data], { type: 'text/plain' });
  download(blob, getFileNameFromContentDisposition(res.headers.get('Content-Disposition')) || 'log.log');
};

defineExpose({
  onOpen,
});
</script>
<style lang="less" scoped>
.task-log {
  .footer {
    display: flex;
    justify-content: space-between;
    color: #2590ff;
    .download {
      cursor: pointer;
    }
    .close-btn {
      width: 88px;
    }
  }

  :deep(.ant-modal-footer) {
    padding: 0px 20px 20px 20px;
    border-top: none !important;
  }
}
</style>
